public class TreeToString_0316 {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }
    public String tree2str(TreeNode root) {
        StringBuilder stringBuilder = new StringBuilder();
        build(root, stringBuilder);
        return stringBuilder.toString();
    }
    private void build(TreeNode root,StringBuilder stringBuilder) {
        if (root == null) return;
        stringBuilder.append(root.val);
        if (root.left != null) {
            stringBuilder.append('(');
            build(root.left,stringBuilder);
            stringBuilder.append(')');
        } else {
            if (root.right == null) {
                stringBuilder.append("()");
            } else {
                return;
            }
        }
        if (root.right != null) {
            stringBuilder.append("(");
            build(root.right,stringBuilder);
            stringBuilder.append(")");
        } else {
            return;
        }
    }
}
